package com.windowes.weichang.exception;

import com.windowes.weichang.common.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ServerResponse exceptionHandler(HttpServletRequest request, Exception e) {
        log.error("错误是:", e);
        if (e instanceof HttpMediaTypeNotSupportedException) {
            HttpMediaTypeNotSupportedException ex = (HttpMediaTypeNotSupportedException) e;
            String detail = "参数错误,请检查数据格式json 或者 form ?";
            return ServerResponse.createByErrorMessage(detail);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            HttpRequestMethodNotSupportedException ex = (HttpRequestMethodNotSupportedException) e;
            return ServerResponse.createByErrorMessage("接口访问方式错误,你确定是【" + ex.getMethod() + "】吗?");
        } else if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return ServerResponse.createByErrorMessage(ex.getMessage());
        } else {
            return ServerResponse.createByErrorMessage("系统异常,请联系管理员!");
        }
    }
}
